package com.zzw.filter;

import com.alibaba.fastjson.JSON;
import com.zzw.entity.Result;
import com.zzw.utils.WarehouseConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Project: warehouse
 * @Description: 登录限制过滤器
 * @Author: zzw
 */
@Slf4j
public class SecurityFilter implements Filter {

    //将Redis模板定义为其成员变量
    private StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 过滤器拦截到请求执行的方法
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求url接口
        String path = request.getServletPath();

        /*
         * 白名单请求直接放行
         */
        List<String> urlList = new ArrayList<String>();
        urlList.add("/captcha/captchaImage");
        urlList.add("/login");
        urlList.add("/logout");
        //对上传图片的url接口/product/img-upload的请求直接放行
        urlList.add("/product/img-upload");
        //放行api文档
        urlList.add("/doc.html");
        urlList.add("/swagger-resources");
        urlList.add("/favicon.ico");
        urlList.add("/v2/api-docs");
        //对static下的img/upload中的静态资源图片的访问和api文档的访问直接放行
        if (urlList.contains(path) || path.contains("/img/upload") || path.startsWith("/webjars/")) {
            filterChain.doFilter(request, response);
            return;
        }

        /*
        其它请求都校验token
         */
        //拿到前端返回的token
        String clientToken = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        //校验token,校验通过放行
        if (StringUtils.hasText(clientToken) && Boolean.TRUE.equals(redisTemplate.hasKey(clientToken))) {
            filterChain.doFilter(request, response);
        }
        //校验失败，向前端响应失败的Result对象转成的json串
        Result result = Result.err(Result.CODE_ERR_UNLOGINED, "请登录！");
        String jsonStr = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
    }
}
